<?php
namespace app\usercp\controller;

use app\usercp\exception\UsercpException;
use think\Request;

class Comment extends Usercp
{
    public function initialize() {
        parent::initialize();
        $this->service = model('article/Comment', 'service');
    }

    /**
     * 评论列表
     */
    public function index(Request $request)
    {

        if ($request->isAjax()){
            $field = $this->request->param('field/s',true);
            $relations = array_filter($this->request->param('relations/a',[]));
            $attrs = array_filter($this->request->param('attrs/a',[]));
            $maps = [];
            $maps['current_id'] = $this->custom['current_id'];
            if ($request->has('site_id','param',true)){
                $maps['site_id'] = $request->param('site_id');
            }
            if ($request->has('keywords','param',true)){
                $maps['keywords'] = $request->param('keywords');
            }
            if ($request->has('article_id','param',true)){
                $maps['article_id'] = $request->param('article_id');
            }
            if ($request->has('status','param',true)){
                $maps['status'] = $request->param('status');
            }
            $list = $this->service->lists($maps,'update_time DESC',$this->page,$this->limit,$field,$relations,$attrs);
            if ($list->isEmpty()){
                return $this->result('',0,'暂无数据');
            }
            //注意：此处状态码一定和前端配置的状态码相同，否则数据会出问题(正常返回200，错误返回0)
            return $this->result($list,200);
        }
        return $this->fetch('index');
    }

    /**
     * 删除评论
     */
    public function delete(Request $request)
    {
        if ($request->isAjax()) {
            $validate = new \app\article\validate\Comment;
            if(!$validate->scene('del')->check($request->post())){
                return $this->result('',0,$validate->getError());
            }
            $current_id = $this->custom['current_id'];
            $result = $this->service->destroy($request->post('id'), $current_id);
            if ($result === false) {
                return $this->result('',0,$this->service->getError());
            }
            return $this->result($result,200,'删除成功');
        }
        return $this->fetch('delete'); 
    }

}